/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import entities.Company;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Market;
import entities.Stock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Juan
 */
public class CompanyJpaController implements Serializable {

    private static CompanyJpaController instance;
    
    public synchronized static CompanyJpaController getInstance(){
        if(instance == null){
            instance = new CompanyJpaController();
        }
        return instance;
    }
    
    public CompanyJpaController() {
        this.emf = Persistence.createEntityManagerFactory("JavaApplication9PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Company company) {
        if (company.getStockCollection() == null) {
            company.setStockCollection(new ArrayList<Stock>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Market idmarket = company.getIdmarket();
            if (idmarket != null) {
                idmarket = em.getReference(idmarket.getClass(), idmarket.getId());
                company.setIdmarket(idmarket);
            }
            Collection<Stock> attachedStockCollection = new ArrayList<Stock>();
            for (Stock stockCollectionStockToAttach : company.getStockCollection()) {
                stockCollectionStockToAttach = em.getReference(stockCollectionStockToAttach.getClass(), stockCollectionStockToAttach.getId());
                attachedStockCollection.add(stockCollectionStockToAttach);
            }
            company.setStockCollection(attachedStockCollection);
            em.persist(company);
            if (idmarket != null) {
                idmarket.getCompanyCollection().add(company);
                idmarket = em.merge(idmarket);
            }
            for (Stock stockCollectionStock : company.getStockCollection()) {
                Company oldIdcompanyOfStockCollectionStock = stockCollectionStock.getIdcompany();
                stockCollectionStock.setIdcompany(company);
                stockCollectionStock = em.merge(stockCollectionStock);
                if (oldIdcompanyOfStockCollectionStock != null) {
                    oldIdcompanyOfStockCollectionStock.getStockCollection().remove(stockCollectionStock);
                    oldIdcompanyOfStockCollectionStock = em.merge(oldIdcompanyOfStockCollectionStock);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Company company) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Company persistentCompany = em.find(Company.class, company.getId());
            Market idmarketOld = persistentCompany.getIdmarket();
            Market idmarketNew = company.getIdmarket();
            Collection<Stock> stockCollectionOld = persistentCompany.getStockCollection();
            Collection<Stock> stockCollectionNew = company.getStockCollection();
            List<String> illegalOrphanMessages = null;
            for (Stock stockCollectionOldStock : stockCollectionOld) {
                if (!stockCollectionNew.contains(stockCollectionOldStock)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Stock " + stockCollectionOldStock + " since its idcompany field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idmarketNew != null) {
                idmarketNew = em.getReference(idmarketNew.getClass(), idmarketNew.getId());
                company.setIdmarket(idmarketNew);
            }
            Collection<Stock> attachedStockCollectionNew = new ArrayList<Stock>();
            /*for (Stock stockCollectionNewStockToAttach : stockCollectionNew) {
                stockCollectionNewStockToAttach = em.getReference(stockCollectionNewStockToAttach.getClass(), stockCollectionNewStockToAttach.getId());
                attachedStockCollectionNew.add(stockCollectionNewStockToAttach);
            }*/
            stockCollectionNew = attachedStockCollectionNew;
            company.setStockCollection(stockCollectionNew);
            company = em.merge(company);
            if (idmarketOld != null && !idmarketOld.equals(idmarketNew)) {
                idmarketOld.getCompanyCollection().remove(company);
                idmarketOld = em.merge(idmarketOld);
            }
            if (idmarketNew != null && !idmarketNew.equals(idmarketOld)) {
                idmarketNew.getCompanyCollection().add(company);
                idmarketNew = em.merge(idmarketNew);
            }
            for (Stock stockCollectionNewStock : stockCollectionNew) {
                if (!stockCollectionOld.contains(stockCollectionNewStock)) {
                    Company oldIdcompanyOfStockCollectionNewStock = stockCollectionNewStock.getIdcompany();
                    stockCollectionNewStock.setIdcompany(company);
                    stockCollectionNewStock = em.merge(stockCollectionNewStock);
                    if (oldIdcompanyOfStockCollectionNewStock != null && !oldIdcompanyOfStockCollectionNewStock.equals(company)) {
                        oldIdcompanyOfStockCollectionNewStock.getStockCollection().remove(stockCollectionNewStock);
                        oldIdcompanyOfStockCollectionNewStock = em.merge(oldIdcompanyOfStockCollectionNewStock);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = company.getId();
                if (findCompany(id) == null) {
                    throw new NonexistentEntityException("The company with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Company company;
            try {
                company = em.getReference(Company.class, id);
                company.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The company with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Stock> stockCollectionOrphanCheck = company.getStockCollection();
            for (Stock stockCollectionOrphanCheckStock : stockCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Company (" + company + ") cannot be destroyed since the Stock " + stockCollectionOrphanCheckStock + " in its stockCollection field has a non-nullable idcompany field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Market idmarket = company.getIdmarket();
            if (idmarket != null) {
                idmarket.getCompanyCollection().remove(company);
                idmarket = em.merge(idmarket);
            }
            em.remove(company);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Company> findCompanyEntities() {
        return findCompanyEntities(true, -1, -1);
    }

    public List<Company> findCompanyEntities(int maxResults, int firstResult) {
        return findCompanyEntities(false, maxResults, firstResult);
    }

    private List<Company> findCompanyEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Company.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Company findCompany(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Company.class, id);
        } finally {
            em.close();
        }
    }

    public int getCompanyCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Company> rt = cq.from(Company.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
